{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Unsupervised Graph Learning with BipartiteGraphSage\n",
    "\n",
    "\n",
    "Bipartite graphs are very common in e-commerce recommendation. In this tutorial, we demostrate how GraphScope trains a model with BipartiteGraphSage on bipartite graph.\n",
    "\n",
    "The task is link prediction, which estimates the probability of links between user and item nodes in a graph.\n",
    "\n",
    "In this task, we use our implementation of BipartiteGraphSage algorithm to build a model that predicts user-item links in the [U2I](http://graph-learn-dataset.oss-cn-zhangjiakou.aliyuncs.com/u2i.zip) dataset. In which nodes can represents user node and item node. The task can be treated as a unsupervised link prediction on a homogeneous link network.\n",
    "\n",
    "In this task, BipartiteGraphSage algorithm would compress both structural and attribute information in the graph into low-dimensional embedding vectors on each node. These embeddings can be further used to predict links between nodes.\n",
    "\n",
    "This tutorial has following steps:\n",
    "\n",
    "- Launching the learning engine and attaching to loaded graph.\n",
    "- Defining train process with builtin GraphSage model and hyperparameters\n",
    "- Training and evaluating\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install graphscope package if you are NOT in the Playground\n",
    "\n",
    "!pip3 install graphscope\n",
    "!pip3 uninstall -y importlib_metadata  # Address an module conflict issue on colab.google. Remove this line if you are not on colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Import the graphscope module.\n",
    "\n",
    "import graphscope\n",
    "\n",
    "graphscope.set_option(show_log=False)  # enable logging"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load u2i dataset\n",
    "\n",
    "from graphscope.dataset import load_u2i\n",
    "\n",
    "graph = load_u2i()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Launch learning engine \n",
    "Then, we need to define a feature list for training. The training feature list should be seleted from the vertex properties. In this case, we choose the \"feature\" property as the training features.\n",
    "\n",
    "With the featrue list, next we launch a learning engine with the [graphlearn](https://graphscope.io/docs/reference/session.html#graphscope.Session.graphlearn) method of graphscope. \n",
    "\n",
    "In this case, we specify the BipartiteGraphSage training over \"u\" and \"i\" nodes and \"u-i\" edges."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# launch a learning engine.\n",
    "\n",
    "lg = graphscope.graphlearn(\n",
    "    graph,\n",
    "    nodes=[(\"u\", [\"feature\"]), (\"i\", [\"feature\"])],\n",
    "    edges=[((\"u\", \"u-i\", \"i\"), [\"weight\"]), ((\"i\", \"u-i_reverse\", \"u\"), [\"weight\"])],\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "We use the builtin BipartiteGraphSage model to define the training process. You can find more detail about all the builtin learning models on [Graph Learning Model](https://graphscope.io/docs/learning_engine.html#data-model)\n",
    "\n",
    "In the example, we use tensorflow as NN backend trainer.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import graphscope.learning\n",
    "from graphscope.learning.examples import BipartiteGraphSage\n",
    "from graphscope.learning.graphlearn.python.model.tf.optimizer import get_tf_optimizer\n",
    "from graphscope.learning.graphlearn.python.model.tf.trainer import LocalTFTrainer\n",
    "\n",
    "\n",
    "# Unsupervised GraphSage.\n",
    "def train(config, graph):\n",
    "    def model_fn():\n",
    "        return BipartiteGraphSage(\n",
    "            graph,\n",
    "            config[\"batch_size\"],\n",
    "            config[\"hidden_dim\"],\n",
    "            config[\"output_dim\"],\n",
    "            config[\"hops_num\"],\n",
    "            config[\"u_neighs_num\"],\n",
    "            config[\"i_neighs_num\"],\n",
    "            u_features_num=config[\"u_features_num\"],\n",
    "            u_categorical_attrs_desc=config[\"u_categorical_attrs_desc\"],\n",
    "            i_features_num=config[\"i_features_num\"],\n",
    "            i_categorical_attrs_desc=config[\"i_categorical_attrs_desc\"],\n",
    "            neg_num=config[\"neg_num\"],\n",
    "            use_input_bn=config[\"use_input_bn\"],\n",
    "            act=config[\"act\"],\n",
    "            agg_type=config[\"agg_type\"],\n",
    "            need_dense=config[\"need_dense\"],\n",
    "            in_drop_rate=config[\"drop_out\"],\n",
    "            ps_hosts=config[\"ps_hosts\"],\n",
    "        )\n",
    "\n",
    "    graphscope.learning.reset_default_tf_graph()\n",
    "    trainer = LocalTFTrainer(\n",
    "        model_fn,\n",
    "        epoch=config[\"epoch\"],\n",
    "        optimizer=get_tf_optimizer(\n",
    "            config[\"learning_algo\"], config[\"learning_rate\"], config[\"weight_decay\"]\n",
    "        ),\n",
    "    )\n",
    "\n",
    "    trainer.train()\n",
    "    u_embs = trainer.get_node_embedding(\"u\")\n",
    "    np.save(\"u_emb\", u_embs)\n",
    "    i_embs = trainer.get_node_embedding(\"i\")\n",
    "    np.save(\"i_emb\", i_embs)\n",
    "\n",
    "\n",
    "# Define hyperparameters\n",
    "config = {\n",
    "    \"batch_size\": 128,\n",
    "    \"hidden_dim\": 128,\n",
    "    \"output_dim\": 128,\n",
    "    \"u_features_num\": 1,\n",
    "    \"u_categorical_attrs_desc\": {\"0\": [\"u_id\", 10000, 64]},\n",
    "    \"i_features_num\": 1,\n",
    "    \"i_categorical_attrs_desc\": {\"0\": [\"i_id\", 10000, 64]},\n",
    "    \"hops_num\": 1,\n",
    "    \"u_neighs_num\": [10],\n",
    "    \"i_neighs_num\": [10],\n",
    "    \"neg_num\": 10,\n",
    "    \"learning_algo\": \"adam\",\n",
    "    \"learning_rate\": 0.001,\n",
    "    \"weight_decay\": 0.0005,\n",
    "    \"epoch\": 5,\n",
    "    \"use_input_bn\": True,\n",
    "    \"act\": tf.nn.leaky_relu,\n",
    "    \"agg_type\": \"gcn\",\n",
    "    \"need_dense\": True,\n",
    "    \"drop_out\": 0.0,\n",
    "    \"ps_hosts\": None,\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run training process\n",
    "\n",
    "After define training process and hyperparameters,\n",
    "\n",
    "Now we can start the traning process with learning engine \"lg\" and the hyperparameters configurations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "train(config, lg)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
